#include "D3DApp.h"
#include "Game.h"

VOID WINAPI CF (D3DXVECTOR4* pOut, const D3DXVECTOR2* pTexCoord, 
	const D3DXVECTOR2* pTexelSize, LPVOID pData)
{
	int x =pTexCoord->x/pTexelSize->x;
	int y =(pTexCoord->y/pTexelSize->y);
	y*=(1/pTexelSize->y);
	D3DCOLORVALUE* color = (D3DCOLORVALUE*)pData;
	D3DCOLORVALUE c=color[x+y];
	*pOut = D3DXVECTOR4(c.r,c.g,c.b,c.a);
}
D3DApp::~D3DApp()
{

}

void D3DApp::Init(HWND hWnd)
{
	m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

	D3DPRESENT_PARAMETERS d3dpp;    // create a struct to hold various device information

	ZeroMemory(&d3dpp, sizeof(d3dpp));    // clear out the struct for use
	d3dpp.Windowed = TRUE;    // program windowed, not fullscreen
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;    // discard old frames
	d3dpp.hDeviceWindow = hWnd;    // set the window to be used by Direct3D
	d3dpp.BackBufferHeight = 600;
	d3dpp.BackBufferWidth = 800;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

	d3dpp.EnableAutoDepthStencil = TRUE;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

	// create a device class using this information and the info from the d3dpp stuct
	m_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		hWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp,
		&m_pD3DDev);

	//vertex decleration
	D3DVERTEXELEMENT9 v[4]=
	{
		{0,0,D3DDECLTYPE_FLOAT3,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_POSITION,0 },
		{0,12,D3DDECLTYPE_FLOAT3,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_NORMAL,0 },
		{0,24,D3DDECLTYPE_FLOAT2,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_TEXCOORD,0 },
		D3DDECL_END()
	};
	
	m_VertexElements[0]=v[0];
	m_VertexElements[1]=v[1];
	m_VertexElements[2]=v[2];
	m_VertexElements[3]=v[3];
	IDirect3DVertexDeclaration9* pdecl;
	TheD3DApp::Instance()->GetD3DDev()->CreateVertexDeclaration(m_VertexElements,&pdecl);
	TheGame::Instance()->m_VertexDec = pdecl;
	TheD3DApp::Instance()->GetD3DDev()->SetVertexDeclaration(TheGame::Instance()->m_VertexDec);
}

LPDIRECT3D9 D3DApp::GetD3D() const
{
	return m_pD3D;
}
LPDIRECT3DDEVICE9 D3DApp::GetD3DDev() const
{
	return m_pD3DDev;
}
HWND D3DApp::GetWindowHandle() const
{
	HWND hWnd;
	hWnd = FindWindow(NULL, L"hWnd");
	return hWnd;
}
D3DVERTEXELEMENT9* D3DApp::GetVertexElements()
{
	return m_VertexElements;
}

void D3DApp::Clean()
{
	m_pD3DDev->Release();
	m_pD3D->Release();
}